package com.zdlog.ler.service.impl;

import com.zdlog.ler.Resp.object.ResponeMessage;
import com.zdlog.ler.Resp.util.ResponeMessageUtil;
import com.zdlog.ler.constant.CookieConstant;
import com.zdlog.ler.constant.RedisConstant;
import com.zdlog.ler.dao.LerUserDao;
import com.zdlog.ler.entity.LerUser;
import com.zdlog.ler.service.LerUserService;
import com.zdlog.ler.util.CookieUtil;
import com.zdlog.ler.util.EmailUtil;
import com.zdlog.ler.util.TextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LerUserServiceImpl implements LerUserService {

    @Autowired
    private LerUserDao lerUserDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender jms;


    @Override
    public LerUser findUserInfoByUserId(String userId) {
        return lerUserDao.findByUserId(userId);
    }

    @Override
    public ResponeMessage register(LerUser lerUser) {
        if (!LerUser.checkRegist(lerUser)) {
            return ResponeMessageUtil.PARAMETER_ERROR();
        }
        if (lerUserDao.findByE_mail(lerUser.getEMail()) != null) {
            return ResponeMessageUtil.USER_IS_HAVE();
        }
        lerUser.setUserId(UUID.randomUUID().toString());
        lerUser.setName(lerUser.getName().trim());
        lerUser.setPassword(TextUtil.encodePassword(lerUser.getPassword()));
        lerUser.setEMail(lerUser.getEMail().trim());
        lerUser.setCreate_time(new Date());
        LerUser user = lerUserDao.save(lerUser);
        if (user != null) {
            return ResponeMessageUtil.REGISTER_SUCCESS();
        } else {
            return ResponeMessageUtil.REGISTER_FAIL();
        }
    }

    @Override
    public ResponeMessage login(HttpServletResponse response, LerUser lerUser) {
        if (!LerUser.checkLogin(lerUser)) {
            return ResponeMessageUtil.PARAMETER_ERROR();
        }
        LerUser user = lerUserDao.findByE_mail(lerUser.getEMail());
        if (user == null) {
            return ResponeMessageUtil.NOT_FOUND_USER();
        }
        if (user.getPassword().equals(TextUtil.encodePassword(lerUser.getPassword()))) {
            //2. 设置token至redis
            String token = UUID.randomUUID().toString();
            Integer expire = RedisConstant.EXPIRE;

            redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token ),user.getUserId() , expire, TimeUnit.SECONDS);

            //3. 设置token至cookie
            CookieUtil.set(response, CookieConstant.TOKEN, token, expire);
            return ResponeMessageUtil.LOGIN_SUCCESS();
        } else {
            return ResponeMessageUtil.LOGIN_FAIL();
        }
    }

    @Override
    public ResponeMessage logout(HttpServletRequest request, HttpServletResponse response) {
        //1. 从cookie里查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //2. 清除redis
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));

            //3. 清除cookie
            CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
        }
        return ResponeMessageUtil.LOGOUT_SUCCESS();
    }

    @Override
    public ResponeMessage sendEmail(LerUser lerUser) {
        if (!LerUser.checkSendMail(lerUser)) {
            return ResponeMessageUtil.PARAMETER_ERROR();
        }
        Long saveExpire = redisTemplate.getExpire(RedisConstant.CODE_PREFIX.substring(0,RedisConstant.CODE_PREFIX.length()-2)+lerUser.getEMail());
        if (saveExpire!=null &&saveExpire>0) {
            return ResponeMessageUtil.SEND_EMAIL_FREQUENTLY();
        }
        int code = EmailUtil.makeAuthCode();
        if (EmailUtil.sendEmail(jms,lerUser, code)) {
            Integer expire = RedisConstant.REGISTER_TIME;
            redisTemplate.opsForValue().set(String.format(RedisConstant.CODE_PREFIX,lerUser.getEMail()),String.valueOf(code) , expire, TimeUnit.SECONDS);
        }else {
            return ResponeMessageUtil.error("未知错误");
        }
        return ResponeMessageUtil.success();
    }





}
